package com.woody.aggregate.application.service.shop.es.strategy.impl;

import com.woody.aggregate.common.consts.es.ShopChangeTypeEnum;
import com.woody.aggregate.common.enums.ShopPropertyTypeEnum;
import com.woody.aggregate.infrastructure.saas.entity.SaasShopConfig;
import com.woody.aggregate.infrastructure.shop.es.esdoc.ShopInfo;
import com.woody.base.user.api.vo.BaseMerchantVO;
import com.woody.base.user.api.vo.ShopVO;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Nonnull;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 商圈信息转换策略
 *
 * @author wénkǎi.zhāng
 */
@Component
public class ShopAddConverterStrategy extends AbstractBaseShopConverterStrategy {


    @Override
    public ShopChangeTypeEnum getStrategyType() {
        return ShopChangeTypeEnum.ADD;
    }

    /**
     * 转换门店信息
     *
     * @param shopVOList        门店信息列表
     * @param esShopInfoMap     ES中已存在的门店信息Map
     * @param merchantMap       商户配置信息Map
     * @param saasShopConfigMap 商圈配置信息Map
     * @return 转换后的ES门店信息列表
     */
    @Override
    @Nonnull
    public List<ShopInfo> convert(List<ShopVO> shopVOList, Map<Long, ShopInfo> esShopInfoMap, Map<Long, BaseMerchantVO> merchantMap, Map<Long, SaasShopConfig> saasShopConfigMap) {
        if (CollectionUtils.isEmpty(shopVOList)) {
            return Collections.emptyList();
        }

        // 新建商圈、门店列表
        List<ShopInfo> shopInfoList = new ArrayList<>();

        List<ShopInfo> shopInfos = shopVOList.stream().map(dbShopInfo -> {
            ShopInfo esShopInfo = new ShopInfo();

            // 设置门店基础信息
            setShopBaseInfo(esShopInfo, dbShopInfo);

            // 文档创建时间保持原来的时间
            if (esShopInfoMap.containsKey(dbShopInfo.getShopId())) {
                esShopInfo.setEsCreateTime(esShopInfoMap.get(dbShopInfo.getShopId()).getEsCreateTime());
            }

            // 不是精选门店，直接返回
            if (!ShopPropertyTypeEnum.isVipShop(dbShopInfo.getProperty())) {
                return esShopInfo;
            }

            // 设置精选门店授权时间
            setVipAuthTime(esShopInfo, dbShopInfo, merchantMap);

            // 设置展示方式
            setDisplayType(esShopInfo, dbShopInfo, saasShopConfigMap);

            // 如果是新增主门店，需要创建相应的商圈
            if (ShopPropertyTypeEnum.isMainShop(dbShopInfo.getProperty())) {
                ShopInfo bdShop = createBdShop(esShopInfo, saasShopConfigMap);
                shopInfoList.add(bdShop);
            }

            return esShopInfo;
        }).collect(Collectors.toList());

        shopInfoList.addAll(shopInfos);

        return shopInfoList;
    }

}
